<script setup lang="ts">
import { nextTick, reactive, ref, toRaw } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { useEventChannel } from "@/hooks/page";
import { filter_0_api } from "@/package/other/api/destination";
import { getGlobalPosition } from "@/utils/location";
import { openSetting } from "@/utils/authorize";
import { Storage } from "@/utils/database";
import { Toast } from "@/utils/toast";

const historyKey = "destination-history";

import IndexTabItem from "./components/index-tab-item.vue";

onLoad(() => {
  historyList.value = Storage.getSync(historyKey) || [];
  reloadPosition()
    .then(() => reloadData())
    .catch(() => reloadData());
});
onUnload(() => eventChannel?.emit("ev-destination-data", ""));

const reloadData = () => {
  return filter_0_api().then((resp) => {
    tabList.value = resp.type_list;
    tempData.destinationData = resp;
    tabClick(tabIndex.value);
  });
};

const reloadPosition = () => {
  return new Promise<void>((resolve, reject) => {
    getGlobalPosition((resp) => {
      positionData.id = resp.cityId;
      positionData.name = resp.cityName;
      resolve();
    }, reject);
  });
};

const positionData = reactive({ id: "", name: "" });
const positionClick = () => {
  positionData.id
    ? pickerCallback({ ...toRaw(positionData), level: 2 })
    : openSetting(["scope.userLocation"], ([auth]) => {
        if (!auth) return;
        reloadPosition().then(() => reloadData());
      });
};

const tabIndex = ref(0);
const tabList = ref<any[]>([]);
const tabClick = (index: number) => {
  tabIndex.value = index;
  destinationList.value = tempData.destinationData[tabList.value[index].key];
};

const historyList = ref<any[]>([]);
const historyClick = (index: number) => {
  pickerCallback(historyList.value[index]);
};

const destinationList = ref<any[]>([]);
const destinationClick = (index: number, index2: number) => {
  pickerCallback(destinationList.value[index].city_list[index2]);
};

const pickerCallback = (e: { id: string; name: string; level: number }) => {
  const data = { id: e.id, name: e.name, level: e.level };
  eventChannel?.emit("ev-destination-data", data);

  nextTick(() => {
    const _historyList = historyList.value;
    const index = _historyList.findIndex((i) => i.id === data.id);
    if (index !== -1) _historyList.splice(index, 1);
    _historyList.unshift(data);
    historyList.value = _historyList.splice(0, 6);
    Storage.setSync(historyKey, toRaw(historyList.value));
  });
};

const eventChannel = useEventChannel(() => {
  eventChannel?.once("ev-destination-data", (resp) => {
    console.log("ev-destination-data", resp);
    uni.setNavigationBarTitle({ title: resp.title });
  });
});

const tempData = { destinationData: {} as any };
</script>

<template>
  <view class="index-tab">
    <view
      class="index-tab-item"
      v-for="(i, d) of tabList"
      :key="i.key"
      @click="tabClick(d)"
    >
      <IndexTabItem :text="i.name" :isActive="tabIndex === d" />
    </view>
  </view>

  <view class="index-data">
    <view class="index-data-group">
      <view class="index-data-title">定位</view>
      <view class="index-data-wrapper">
        <view class="index-data-position" @click="positionClick">
          <image
            class="index-data-position2"
            src="@/package/other/static/destination-index-position.png"
          />
          {{ positionData.id ? positionData.name : "定位" }}
        </view>
      </view>
    </view>

    <view
      class="index-data-group"
      v-if="historyList.length !== 0 && tabIndex === 0"
    >
      <view class="index-data-title">历史选择</view>
      <view class="index-data-wrapper">
        <view
          class="index-data-item"
          v-for="(i, d) of historyList"
          :key="i.id"
          @click="historyClick(d)"
        >
          {{ i.name }}
        </view>
      </view>
    </view>

    <view class="index-data-group" v-for="(i, d) of destinationList" :key="d">
      <view class="index-data-title">{{ i.name }}</view>
      <view class="index-data-wrapper">
        <view
          class="index-data-item"
          v-for="(j, x) of i.city_list"
          :key="j.id"
          @click="destinationClick(d, x)"
        >
          {{ j.name }}
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  padding-top: 20rpx;
  background-color: #ffffff;
}

.index-tab {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  width: 160rpx;
  background-color: #f6f7f8;
  z-index: 9;
}

.index-data {
  padding-left: 190rpx;

  .index-data-group {
    position: relative;
  }

  .index-data-title {
    margin-bottom: 30rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 44rpx;
    font-weight: bold;
  }

  .index-data-wrapper {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 20rpx;
  }

  .index-data-position,
  .index-data-item {
    width: 160rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    font-size: 28rpx;
    color: #333333;
    line-height: 60rpx;
    text-align: center;
    border-radius: 20rpx;
    background-color: #f5f6f8;
  }

  .index-data-position {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60rpx;
  }

  .index-data-position2 {
    width: 28rpx;
    height: 28rpx;
    margin-right: 10rpx;
  }

  .index-data-item {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
}
</style>